//
//  HMUserAccount.swift
//  MicroBlog
//
//  Created by Apple on 16/9/22.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archiver")

class HMUserAccount: NSObject, NSCoding{
    //用户授权的唯一票据
    var access_token: String?
    //access_token的生命周期,单位秒
    var expires_in: TimeInterval = 0 {
        didSet {
            //过期时间= 当前时间 + 过期秒数
            expiresDate = Date().addingTimeInterval(expires_in)
        }
    }
    //过期时间
    var expiresDate: Date?
    //授权用户的uid
    var uid: Int64 = 0
    //用户名
    var name: String?
    //用户头像
    var avatar_hd: String?
    //KVC构造函数
    init(dic: [String:Any]) {
        super.init()
        setValuesForKeys(dic)
    }
    //字段不匹配防止报错
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    // 归档和解档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_hd, forKey: "avatar_hd")
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_hd = aDecoder.decodeObject(forKey: "avatar_hd") as? String
    }
    
    //保存当前用户对象
    func saveUserInfo() {
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    //从指定沙盒路径获取用户信息
    class func loadUserAccount() -> HMUserAccount?{
        return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? HMUserAccount
    }
}


